#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: tpf_inspects_v1.py 
@version:
@time: 2022/04/18 
"""
from TapUtil.decorator.some_useful import timeout
from TapUtil.logfunc.logger import logger

from TapClientCore.T06_Tapdata_feature.v2.TPF04_inspects.tpf_inspects_base import TPFInspectsBASE
from TapException.TM import *


class V2TPFInspects(TPFInspectsBASE):
    inspect_url = None

    def _create_inspects_mission(self, data):
        """
        创建一个数据校验任务
        :param data:
        :return:
        """
        record = {}
        response = self.TMF_INSPECTS.create_inspect(data)
        record['id'] = response.get('data').get('id')
        record['create_response'] = response
        return record

    def create_inspects_mission(self, data):
        table = data.get('table')
        if not isinstance(table, list):
            table = [table]
            data['table'] = table
        task_node_setting = data.get('task_node_setting')
        inspect_setting = data.get('inspect_setting')
        inspect_name = inspect_setting.get('name')
        from TapClientCore.T05_TM_feature.v2.TMF03_task.tmf_task import TMFTask
        task_info = TMFTask().query_task_by_name(inspect_name)
        task_more_info = TMFTask().query_task_by_id(task_info.get('id'))
        nodes = task_more_info.get('data').get('dag').get('nodes')

        inspects_info = self.post_meta_find_inspects(data, nodes)

        create_data = {
            'tasks': inspects_info,
            'inspect_setting': {
                **inspect_setting,
            }
        }
        repeat = self.TMF_INSPECTS.inspects_check_name_repeat(inspect_name)
        if repeat:
            logger.info("同名Inspects已存在")
            try:
                logger.info("删除旧任务")
                self.TMF_INSPECTS.delete_inspects_by_name(inspect_name)
                self.inspects_delete_mongodb({
                    'name': inspect_name
                })
            except Exception as e:
                assert False
        logger.info(f'{inspect_name}创建校验任务，并将记录持久化')
        record = self._create_inspects_mission(create_data)
        self.inspects_insert_mongodb(
            {'name': inspect_name, **record}
        )
        return record

    def _generate_inspect_url_by_name(self, name):
        """
        生成数据校验url
        :param name:
        :return:
        """
        inspect_id = self.TMF_INSPECTS.query_inspect_by_name(name).get('id')
        from TapClientCore.T02_tm_api.v2_api.v2_tm import v2tm as TM
        self.inspect_url = f'{TM.serve}/#/dataVerification/{inspect_id}/details'

    def get_inspect_result(self, name):
        return self.TMF_INSPECTS.query_inspect_by_name(name).get('result')

    def get_inspect_status(self, name):
        return self.TMF_INSPECTS.query_inspect_by_name(name).get('status')

    def get_inspect_source_total(self, name):
        return self.TMF_INSPECTS.query_inspect_by_name(name).get('InspectResult').get('source_total')

    def _get_meta_find_inspects(self, data):
        inq_table = data.get('table')
        source_id = data.get('source_id')
        target_id = data.get('target_id')
        inq_id = [source_id, target_id]
        return self.TMF_META.get_metadataInstances_findInspect(inq_id, inq_table)

    def get_meta_find_inspects(self, data):
        """
        从meta 获取inspects数据
        :param data:
        :return:
        """
        source = data.get('source')
        target = data.get('target')
        source_id = self.TMF_DATASOURCE.get_data_source_by_name(source).get('id')
        target_id = self.TMF_DATASOURCE.get_data_source_by_name(target).get('id')
        data['source_id'] = source_id
        data['target_id'] = target_id
        response = self._get_meta_find_inspects(data).get('data')
        all_source_and_target = []
        for table in data.get('table'):
            tmp_source_and_target = []
            tmp_source_and_target_dict = {}
            for item in response:
                if item.get('original_name') == table:
                    tmp_source_and_target.append(item)
            if tmp_source_and_target[0].get('source').get('name') == source:
                tmp_source_and_target_dict['source'] = {
                    "connectionId": source_id,
                    "connectionName": source,
                    "table": table,
                    "sortColumn": "pk",
                    "fields": tmp_source_and_target[0].get('fields')
                }
                tmp_source_and_target_dict['target'] = {
                    "connectionId": target_id,
                    "connectionName": target,
                    "table": table,
                    "sortColumn": "pk",
                    "fields": tmp_source_and_target[1].get('fields')
                }
            elif tmp_source_and_target[1].get('source').get('name') == source:
                tmp_source_and_target_dict['source'] = {
                    "connectionId": source_id,
                    "connectionName": source,
                    "table": table,
                    "sortColumn": "pk",
                    "fields": tmp_source_and_target[1].get('fields')
                }
                tmp_source_and_target_dict['target'] = {
                    "connectionId": target_id,
                    "connectionName": target,
                    "table": table,
                    "sortColumn": "pk",
                    "fields": tmp_source_and_target[0].get('fields')
                }

            all_source_and_target.append(tmp_source_and_target_dict)
        return all_source_and_target

    def _post_meta_find_inspects(self, data):
        inq_table = data.get('table')
        source_id = data.get('source_id')
        target_id = data.get('target_id')
        inq_id = [source_id, target_id]
        return self.TMF_META.post_metadataInstances_findInspect(inq_id, inq_table)

    def post_meta_find_inspects(self, data, nodes):
        source = data.get('source')
        target = data.get('target')
        source_id = self.TMF_DATASOURCE.get_data_source_by_name(source).get('id')
        target_id = self.TMF_DATASOURCE.get_data_source_by_name(target).get('id')
        source_node_id = ''
        sink_node_id = ''
        for node in nodes:
            if node.get('connectionId') == source_id:
                source_node_id = node.get('id')
            else:
                sink_node_id = node.get('id')
        data['source_id'] = source_id
        data['target_id'] = target_id
        response = self._post_meta_find_inspects(data).get('data')
        all_source_and_target = []
        for table in data.get('table'):
            tmp_source_and_target = []
            tmp_source_and_target_dict = {}
            for item in response:
                if item.get('original_name') == table:
                    tmp_source_and_target.append(item)
            if tmp_source_and_target[0].get('source').get('name') == source:
                tmp_source_and_target_dict['source'] = {
                    "connectionId": source_id,
                    "connectionName": source,
                    "table": table,
                    "sortColumn": "pk",
                    "fields": tmp_source_and_target[0].get('fields'),
                    'nodeId': source_node_id
                }
                tmp_source_and_target_dict['target'] = {
                    "connectionId": target_id,
                    "connectionName": target,
                    "table": table,
                    "sortColumn": "pk",
                    "fields": tmp_source_and_target[1].get('fields'),
                    'nodeId': sink_node_id
                }
            elif tmp_source_and_target[1].get('source').get('name') == source:
                tmp_source_and_target_dict['source'] = {
                    "connectionId": source_id,
                    "connectionName": source,
                    "table": table,
                    "sortColumn": "pk",
                    "fields": tmp_source_and_target[1].get('fields'),
                    'nodeId': source_node_id
                }
                tmp_source_and_target_dict['target'] = {
                    "connectionId": target_id,
                    "connectionName": target,
                    "table": table,
                    "sortColumn": "pk",
                    "fields": tmp_source_and_target[0].get('fields'),
                    'nodeId': sink_node_id
                }

            all_source_and_target.append(tmp_source_and_target_dict)
        return all_source_and_target


if __name__ == '__main__':
    T = V2TPFInspects()
    data = {
        'source': 'Auto_Test001Sqlserver_Source',
        'target': 'Auto_Test004Sqlserver',
        'table': 'BreakPointB_MS1649993138508995515',
        'task_node_setting': {},
        'inspect_setting': {
            'inspectMethod': 'field',
            'name': 'breakpoint_Auto_Test001Sqlserver_Source2Auto_Test004SqlserverBreakPointB_MS1649993138508995515'
        }
    }
    data1 = 'david_oracle_mongo'
    print(T.get_inspect_source_total(data1))
